﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;

namespace TheServer.Models
{
    public class MessageDAO
    {
        public static int PostMessage(MessageDTO Msg)
        {
            try
            {
                if (Msg.TaiKhoanGui != null && Msg.TaiKhoanNhan != null)
                {
                    List<Message> Mess = MyDatabase.db.Messages.ToList();
                    Message _Msg = new Message();
                    _Msg.TaiKhoanGui = Msg.TaiKhoanGui;
                    _Msg.TaiKhoanNhan = Msg.TaiKhoanNhan;
                    _Msg.NoiDung = Msg.NoiDung;
                    if (Mess.Count() == 0)
                        _Msg.Id = 0;
                    else
                        _Msg.Id = Mess.Last().Id + 1;
                    MyDatabase.db.AddToMessages(_Msg);
                    MyDatabase.db.SaveChanges();
                    return 1;
                }
                return 0;
            }
            catch
            {
                return -1;
            }
        }

        public static List<MessageDTO> GetMessage(string msg)
        {
            try
            {
                List<MessageDTO> msgs = new List<MessageDTO>();
                var _msgs = (from mess in MyDatabase.db.Messages where mess.TaiKhoanNhan.Equals(msg) select mess).ToList();
                for (int i = 0; i < _msgs.Count; i++)
                {
                    MessageDTO mss = new MessageDTO();
                    mss.TaiKhoanGui = _msgs[i].TaiKhoanGui;
                    mss.TaiKhoanNhan = _msgs[i].TaiKhoanNhan;
                    mss.NoiDung = _msgs[i].NoiDung;
                    MyDatabase.db.Messages.DeleteObject(_msgs[i]);
                    MyDatabase.db.SaveChanges();
                    msgs.Add(mss);
                }
                return msgs;
            }
            catch
            {
                return null;
            }
        }
    }
}